
<template>
    <ContentWrap>
        <div class="flex justify-between">
            <div class="flex aic">
                <ElButton type="primary" :icon="Plus" @click="onAdd">
                    {{ t('新增公告') }}
                </ElButton>
            </div>
            <div class="">
                <ElInput v-model="state.searchData.keywords" style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入公告标题" :prefix-icon="Search" />
                <ElButton type="primary" :icon="Search" @click="onSearch">
                    {{ t('common.query') }}
                </ElButton>
                <ElButton :icon="Refresh" @click="onReset">
                    {{ t('common.reset') }}
                </ElButton>

            </div>
        </div>
        <div class="" style="margin-top: 25px;">
            <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
                :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
                :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
        </div>
    </ContentWrap>
    <Dialog v-model="dialogVisible1" :title="state.dialogVisible1title">
        <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            status-icon>
            <div class="flex jcsb">
                <el-form-item label="公告标题" prop="noticeTitle">
                    <el-input v-model="state.ruleForm.noticeTitle" placeholder="请输入公告标题" />
                </el-form-item>
                <el-form-item label="通知范围" prop="">
                    <el-select :disabled="state.dialogVisible1title=='编辑公告'" v-model="state.ruleForm.tenantIds" class="m-2" placeholder="请选择通知范围"  filterable multiple>
                        <el-option v-for="item in state.optionsTenantData" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </div>

            <el-form-item label="公告详情" prop="noticeContent">
                <!-- <Editor v-model="state.ruleForm.noticeContent" placeholder="请输入公告详情"/> -->
                <el-input v-model="state.ruleForm.noticeContent" placeholder="请输入公告详情" :autosize="{ minRows: 2}" type="textarea" row="4" />
            </el-form-item>
            <el-form-item>
                <div class="flex jcfe w-[100%]">
                    <el-button type="primary" @click="submitForm(ruleFormRef)" v-loading="btn_loading">保存</el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </div>
            </el-form-item>
        </el-form>
    </Dialog>
</template>
    
<script setup lang="tsx">
import { Editor } from "@/components/Editor/index"
import { getnoticelistApi, addNoticeApi, editNoticeApi, deteleNoticeApi } from "@/api/notice/index"
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import type { FormInstance, FormRules } from 'element-plus'
import { getTenantListApi } from "@/api/business/index"
import { useRouter } from 'vue-router'
const btn_loading = ref(false)
const { push } = useRouter()
const props = { multiple: true }
interface RuleForm {
    noticeTitle: string
    noticeContent: string
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    noticeTitle: [
        { required: true, message: '请输入公告标题！', trigger: 'blur' },
        { min: 1, max: 50, message: '不超过50字符！', trigger: 'blur' },
    ],
    noticeContent: [
        { min: 1, max: 1000, message: '不超过1000字符！', trigger: 'blur' },
    ]
})
const submitForm = async (formEl: FormInstance | undefined) => {
    // dialogVisible1.value = false
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (state.dialogVisible1title == '新增公告') {
                let obj = {
                    "noticeTitle": state.ruleForm.noticeTitle,
                    "tenantIds": state.ruleForm.tenantIds,
                    "noticeContent": state.ruleForm.noticeContent,
                    "noticeType":"2"
                }
                btn_loading.value = true
                addNoticeApi(obj).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    btn_loading.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    btn_loading.value = false
                })
            } else {
                btn_loading.value = true
                editNoticeApi(state.ruleForm).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    btn_loading.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    btn_loading.value = false
                })
            }
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible1.value = false
    if (!formEl) return
    formEl.resetFields()
}
const { t } = useI18n()
const dialogVisible1 = ref(false)//定义职位详情弹框
const state = reactive({
    searchData: {
        companyValue: "",
        jobValue: "",
        keywords: ""
    },//搜索参数
    optionsTenantData:[] as any,
    react: true,//分页刷新
    dialogVisible1title: "新增公告",
    ruleForm: {} as any,
})
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'noticeTitle',
        label: t('公告标题'),
        search: {
            component: 'Input'
        },
        form: {
            component: 'Input',
            colProps: {
                span: 24
            }
        }
    },
    {
        field: 'noticeContent',
        label: t('公告内容'),
        search: {
            component: 'Input'
        },
        form: {
            component: 'Input',
            colProps: {
                span: 24
            }
        }
    },
    {
        field: 'createByName',
        label: t('创建者'),
        value:"系统",
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.createByName?data[0].row.createByName:"系统"}</div>

                        </>
                    )
                }
            }
        }
    },
    {
        field: 'createTime',
        label: t('创建时间'),
        search: {
            hidden: true
        }
    },
    {
        field: 'action',
        width: '260px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                {t('编辑')}
                            </ElButton>
                            {/* <ElButton link type="primary" onClick={() => receat(data[0].row)}>
                                {t('查看')}
                            </ElButton> */}
                            <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                                {t('删除')}
                            </ElButton>

                        </>
                    )
                }
            }
        }
    }
])

const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
        const { currentPage, pageSize } = tableState
        const res:any = await getnoticelistApi({
            pageNum: state.react ? 1 : unref(currentPage),
            pageSize: unref(pageSize),
            noticeTitle: state.searchData.keywords,
            isAsc:"desc",
            orderByColumn:"createTime"
        })
        console.log(res);
        state.react = false
        return {
            list: res.rows,
            total: res.total
        }
    }
})
// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
getList()
useEmitt({
    name: 'getList',
    callback: (type: string) => {
        if (type === 'add') {
            currentPage.value = 1
        }
        getList()
    }
})
const { allSchemas } = useCrudSchemas(crudSchemas)

// 新增
const onAdd = () => {
    state.ruleForm = {}
    dialogVisible1.value = true
    state.dialogVisible1title = t('新增公告')
}
const action = (row: any) => {
    console.log(row);
    dialogVisible1.value = true
    state.ruleForm=row
    state.ruleForm.tenantIds=[row.tenantId]
    state.dialogVisible1title = t('编辑公告')
}
const delData = (row: any) => {
    ElMessageBox.confirm('确认删除该公告？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    })
        .then(() => {
            deteleNoticeApi(row.noticeId).then((res: any) => {
                getList()
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })

}

// 查询
const onSearch = () => {
    console.log("查询");
    state.react = true
    getList()
}
// 重置
const onReset = () => {
    console.log("重置");
    state.searchData.companyValue = ""
    state.searchData.keywords = ""
    state.searchData.jobValue = ""
    state.react = true
    getList()
}
// 租户下拉框
const getTenantListApi_ = async () => {
    getTenantListApi({ pageNum: 1, pageSize: 10000 }).then((res: any) => {
        console.log("租户", res);
        state.optionsTenantData = []
        res.rows.forEach(element => {
            let obj = {
                label: element.companyName,
                value: element.tenantId
            }
            state.optionsTenantData.push(obj)
        });
        getList()
    })
}
getTenantListApi_()

</script>
    
<style lang="less" scoped></style>